/**
 * Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.xume.raob;

import java.lang.reflect.Proxy;

import org.xume.raob.api.ObjectBuilder;
import org.xume.raob.api.ObjectFactory;
import org.xume.raob.core.IntrospectionResult;
import org.xume.raob.core.ObjectBuilderInvocationHandler;

/**
 * @author Johan Siebens
 */
@SuppressWarnings("unchecked")
public final class ObjectBuilderFactory {

	public static <T, V extends ObjectBuilder<T>> V createBuilder(Class<V> builderInterface) {
		return createBuilder(null, builderInterface);
	}

	public static <T, V extends ObjectBuilder<T>> V createBuilder(ObjectFactory<T> instantiationStrategy,
			Class<V> builderInterface) {
		IntrospectionResult introspection = IntrospectionResult.forBuilder(builderInterface);
		ObjectBuilderInvocationHandler<T> handler = new ObjectBuilderInvocationHandler<T>(instantiationStrategy, introspection);
		return (V) Proxy.newProxyInstance(builderInterface.getClassLoader(), new Class[] { builderInterface }, handler);
	}

	public static <T, V extends ObjectBuilder<T>> V wrap(final T t) {
		return (V) new ObjectBuilder<T>() {

			public T build() {
				return t;
			}

		};
	}

	private ObjectBuilderFactory() {
	}

}
